const { get , getWithPath } = require("../../utils/http")
// pages/index/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: {},
    isPraise: false,
    thumbNums: 0,
    submit: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.id){
      this.loadData(options.id);
      return
    }
    const event =  this.getOpenerEventChannel()
    const that = this
    event.on("indexData" , function(data) {
      that.loadInit(data)
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
   
  },

  loadInit(data){
    const that = this
    const wec = wx
    console.log(data)
    const detail = data
    that.setData({detail:detail})
    wec.setNavigationBarTitle({
      title: detail.title,
      fail: (err)=>{
        console.log(err)
      }
    })
    that.getLikeStatus({targetType:"industry",id:detail.id})
    that.addViewCount(detail.id)
    that.submit = false
  },

  onLike(){
    if(this.submit){
      this.setData({
        thumbNums: 2,
      })
      return
    }
    this.submit = true
    const likeStatus = !this.data.isPraise
    const {id} = this.data.detail
    const that = this
    get("/user/like",{targetType:"industry",id:id , likeStatus: likeStatus?1:0})
    .then(res=>{
      setTimeout(() => {
        that.setData({
          thumbNums: 2,
          isPraise: likeStatus,
        })
        that.submit = false
      }, 1000);
    }).catch(err => {
      wx.showToast({
        title: '网络异常,请稍后再试',
        icon: 'none'
      })
      that.submit = false
    })
  },

  loadData(id){
    getWithPath('/user/industryTrends/{id}',{id:id})
    .then(res=>{
      const data = res.data || {}
      if(data.coverImage){
        if(data.coverImage.includes(",")){
          data.coverImage = data.coverImage.split(",")
        }else{
          data.coverImage = [data.coverImage]
        }
      }
      this.loadInit(data)
    }).catch(err=>{
      wx.showToast({
        title: '网络异常,请稍后再试',
        icon: 'none'
      })
      this.submit = false
    })
  },

  getLikeStatus(opt){
    const that = this
    get("/user/getLikeStatus",opt)
    .then(res=>{
      that.setData({
        isPraise: res.data && res.data == 1
      })
    }).catch(err => {
      wx.showToast({
        title: '网络异常,请稍后再试',
        icon: 'none'
      })
    })
  },
  addViewCount(id){
    getWithPath("/user/industryTrends/view/{id}",{id:id})
    .then(res=>{
      console.log(res)
    }).catch(err => {
      wx.showToast({
        title: '网络异常,请稍后再试',
        icon: 'none'
      })
    })
  }
})